package cc.linker.steplink.crm.commons.oss;

import cc.linker.steplink.crm.commons.model.OssProperties;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
public class ObjectOperations {
	
	public String prefix;
	public String endpoint;
	public String endpoint2;
    public String accessKeyId;
    public String accessKeySecret;
    public String backetName;
    public String imgURL;
    public String httpPath;
    public String expireTimein;
    public String imgRoot;

	public ObjectOperations(OssProperties oss) {
		this.prefix = oss.getPerfix();
		this.endpoint = oss.getEndpoint();
		this.endpoint2 = oss.getEndpoint2();
		this.accessKeyId = oss.getAccessKeyId();
		this.accessKeySecret = oss.getAccessKeySecret();
		this.backetName = oss.getBacketName();
		this.imgURL = oss.getBacketImgUrl();
		this.httpPath = oss.getHttpPath();
		this.expireTimein = oss.getExpireTime();
		this.imgRoot = oss.getImgRoot();
	}
  
	/**
	   * 上传网络流
	   * @param BucketName
	   * @param key
	   * @param content
	   */
	public PutObjectResult upload(String BucketName, String key, InputStream content){
		// 创建OSSClient实例
				OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				// 上传网络流
				PutObjectResult result = ossClient.putObject(backetName, key, content);
				// 关闭client
				ossClient.shutdown();
				return result;
	}
	/**
	   * 上传本地文件
	   * @param BucketName
	   * @param key
	   * @param content
	   */
	public PutObjectResult upload(String BucketName, String key, File content){
		// 创建OSSClient实例
				OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				// 上传本地文件
				PutObjectResult result = ossClient.putObject(BucketName, key, content);
				// 关闭client
				ossClient.shutdown();
				return result;
	}
	
	/**
	   * 创建模拟文件夹
	   * @param BucketName
	   * @param dir
	   * 提示：
	   * 创建模拟文件夹本质上来说是创建了一个名字以“/”结尾的文件；
	   * 对于这个文件照样可以上传下载,只是控制台会对以“/”结尾的文件以文件夹的方式展示；
	   * 多级目录创建最后一级即可，比如dir1/dir2/dir3/，创建dir1/dir2/dir3/即可，dir1/、dir1/dir2/不需要创建；
	   */
	public void createDir(String BucketName, String dir){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		ossClient.putObject(BucketName, dir, new ByteArrayInputStream(new byte[0]));
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 
	 * @param BucketName
	 * @param key
	 * 追加上传的次数没有限制，文件大小上限为5GB。更大的文件请使用分片上传；追加类型的文件(Append Object)暂时不支持copyObject操作。
	 */
	public void append(String BucketName, String key, InputStream inputStream){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		AppendObjectRequest appendObjectRequest = new AppendObjectRequest(BucketName, 
		        key, inputStream);
		// 第一次追加
		appendObjectRequest.setPosition(0L);
		AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest);
		// 第二次追加
		appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
		appendObjectResult = ossClient.appendObject(appendObjectRequest);
		// 第三次追加
		appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
		appendObjectResult = ossClient.appendObject(appendObjectRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 断点续传上传
	 * @param BucketName
	 * @param key
	 * @param path
	 */
	public void uploadBreak(String BucketName, String key, String path){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 设置断点续传请求
		UploadFileRequest uploadFileRequest = new UploadFileRequest(BucketName, key);
		// 指定上传的本地文件
		uploadFileRequest.setUploadFile(path);
		// 指定上传并发线程数
		uploadFileRequest.setTaskNum(5);
		// 指定上传的分片大小
		uploadFileRequest.setPartSize(1 * 1024 * 1024);
		// 开启断点续传
		uploadFileRequest.setEnableCheckpoint(true);
		// 断点续传上传
		try {
			ossClient.uploadFile(uploadFileRequest);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 分片上传
	 * @param BucketName
	 * @param key
	 * @param path
	 */
	public void uploadMultipart(String BucketName, String key, InputStream instream){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(BucketName, key);
		InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request);
		String uploadId = result.getUploadId();
		List<PartETag> partETags = new ArrayList<PartETag>();
		
		UploadPartRequest uploadPartRequest = new UploadPartRequest();
		uploadPartRequest.setBucketName(BucketName);
		uploadPartRequest.setKey(key);
		uploadPartRequest.setUploadId(uploadId);
		uploadPartRequest.setInputStream(instream);
		// 设置分片大小，除最后一个分片外，其它分片要大于100KB
		uploadPartRequest.setPartSize(100 * 1024);
		// 设置分片号，范围是1~10000，
		uploadPartRequest.setPartNumber(1);
		UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
		partETags.add(uploadPartResult.getPartETag());
		Collections.sort(partETags, new Comparator<PartETag>() {
		    @Override
		    public int compare(PartETag p1, PartETag p2) {
		        return p1.getPartNumber() - p2.getPartNumber();
		    }
		});
		CompleteMultipartUploadRequest completeMultipartUploadRequest = 
		        new CompleteMultipartUploadRequest(BucketName, key, uploadId, partETags);
		ossClient.completeMultipartUpload(completeMultipartUploadRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 取消分片上传事件
	 * @param BucketName
	 * @param key
	 * @param inputStream
	 * @param uploadId
	 */
	public void uploadMultipartStop(String BucketName, String key, InputStream inputStream, String uploadId){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		
		ossClient.putObject(BucketName, key,inputStream);
		// 取消分片上传，其中uploadId来自于initiateMultipartUpload
		AbortMultipartUploadRequest abortMultipartUploadRequest = 
		        new AbortMultipartUploadRequest(BucketName, key, uploadId);
		ossClient.abortMultipartUpload(abortMultipartUploadRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 获取已上传的分片
	 * @param BucketName
	 * @param key
	 * @param uploadId
	 * @return
	 */
	public PartListing getMultipartUpload(String BucketName, String key, String uploadId){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 列举已上传的分片，其中uploadId来自于initiateMultipartUpload        
		ListPartsRequest listPartsRequest = new ListPartsRequest(BucketName, key, uploadId);
		PartListing partListing = ossClient.listParts(listPartsRequest);
		for (PartSummary part : partListing.getParts()) {
		    // 分片号，上传时候指定
		    part.getPartNumber();
		    // 分片数据大小
		    part.getSize();
		    // Part的ETag
		    part.getETag();
		    // Part的最后修改上传
		    part.getLastModified();
		}
		// 关闭client
		ossClient.shutdown();
		return partListing;
	}
	/**
	 * Object是否存在
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public boolean exist(String BucketName, String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// Object是否存在
		boolean found = ossClient.doesObjectExist(BucketName, key);

		// 关闭client
		ossClient.shutdown();
		return found;
	}
	/**
	 * 设置Object ACL
	 * Object有四种访问权限：Default（默认），Private（私有读写）, PublicRead（公共读私有写）, PublicReadWrite（公共读写）
	 * @param BucketName
	 * @param key
	 * @param acl
	 */
	public void setACL(String BucketName, String key, CannedAccessControlList acl){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 设置Object权限
		ossClient.setObjectAcl(BucketName, key, acl);

		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 获取文件元信息(Object Meta)
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public ObjectMetadata get(String BucketName, String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取文件的部分元信息
		SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(BucketName, key);
		System.out.println(objectMeta.getSize());
		System.out.println(objectMeta.getETag());
		System.out.println(objectMeta.getLastModified());

		// 获取文件的全部元信息
		ObjectMetadata metadata = ossClient.getObjectMetadata(BucketName, key);
		System.out.println(metadata.getContentType());
		System.out.println(metadata.getLastModified());
		System.out.println(metadata.getObjectType());
		

		// 关闭client
		ossClient.shutdown();
		return metadata;
	}
	
	/**
	 * 获取文件元信息(Object Meta)
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public OSSObject getObject(String BucketName, String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取文件
		OSSObject obj = ossClient.getObject(BucketName, key);
		
		ossClient.shutdown();
		return obj;
	}
	
	/**
	 * 获取文件流信息
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public byte[] getBytes(String BucketName, String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取文件
		OSSObject obj = ossClient.getObject(BucketName, key);
		byte[] b = null;
		try {
			b = IOUtils.readStreamAsByteArray(obj.getObjectContent());
			if(obj.getObjectContent()!=null)
				obj.getObjectContent().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ossClient.shutdown();
		return b;
	}
	
	/**
	 * 列出存储空间内所有文件
	 * @param BucketName
	 * @param page 
	 * @param keyName 
	 * @param type 
	 * @param max
	 * @return 
	 */
	public ObjectListing list(String BucketName, Integer type, String keyName, Integer page){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(BucketName);
		ObjectListing listing=null;
		// 列出Object 
		if(page==null){
		if(type==null)
		 listing = ossClient.listObjects(listObjectsRequest);
		else{
			if(type==0)
				listing = ossClient.listObjects(listObjectsRequest.withPrefix(keyName));
			if(type==1)
				listing = ossClient.listObjects(listObjectsRequest.withMarker(keyName));
		}
		}else{
			if(type==null)
				 listing = ossClient.listObjects(listObjectsRequest.withMaxKeys(page));
				else{
					if(type==0)
						listing = ossClient.listObjects(listObjectsRequest.withPrefix(keyName).withMaxKeys(page));
					if(type==1)
						listing = ossClient.listObjects(listObjectsRequest.withMarker(keyName).withMaxKeys(page));
				}
		}

		// 遍历所有Object
		System.out.println("Objects:");
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
		    System.out.println(objectSummary.getKey());
		}

		// 遍历所有CommonPrefix
		System.out.println("CommonPrefixs:");
		for (String commonPrefix : listing.getCommonPrefixes()) {
		    System.out.println(commonPrefix);
		}
		return listing;
	}
	/**
	 * 删除文件
	 * 每次最多删除1000个Object
	 * @param BucketName
	 * @param keys
	 */
	public void delete(String BucketName, List<String> keys){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		

		DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(BucketName).withKeys(keys));
		List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
		System.out.println(deletedObjects);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 拷贝文件
	 * @param srcBucketName
	 * @param srcKey
	 * @param destBucketName
	 * @param destKey
	 */
	public void copy(String srcBucketName, String srcKey, String destBucketName, String destKey){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 拷贝Object
		CopyObjectResult result = ossClient.copyObject(srcBucketName, srcKey, destBucketName, destKey);
		System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());

		// 关闭client
		ossClient.shutdown();
	}
	
	public void copyPort(String sourceBucketName, String sourceKey, String targetBucketName, String targetKey){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 得到被拷贝object大小
		ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceKey);
		long contentLength = objectMetadata.getContentLength();

		// 分片大小，10MB
		long partSize = 1024 * 1024 * 10;

		// 计算分块数目
		int partCount = (int) (contentLength / partSize);
		if (contentLength % partSize != 0) {
		    partCount++;
		}
		System.out.println("total part count:" + partCount);

		// 初始化拷贝任务
		InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(targetBucketName, targetKey);
		InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest);
		String uploadId = initiateMultipartUploadResult.getUploadId();

		// 分片拷贝
		List<PartETag> partETags = new ArrayList<PartETag>();
		for (int i = 0; i < partCount; i++) {
		     // 计算每个分块的大小
		    long skipBytes = partSize * i;
		    long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes;

		    // 创建UploadPartCopyRequest
		    UploadPartCopyRequest uploadPartCopyRequest = 
		        new UploadPartCopyRequest(sourceBucketName, sourceKey, targetBucketName, targetKey);
		    uploadPartCopyRequest.setUploadId(uploadId);
		    uploadPartCopyRequest.setPartSize(size);
		    uploadPartCopyRequest.setBeginIndex(skipBytes);
		    uploadPartCopyRequest.setPartNumber(i + 1);
		    UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);

		    // 将返回的PartETag保存到List中
		    partETags.add(uploadPartCopyResult.getPartETag());
		}

		// 提交分片拷贝任务
		CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
		                    targetBucketName, targetKey, uploadId, partETags);
		ossClient.completeMultipartUpload(completeMultipartUploadRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 下载到本地文件
	 * @param BucketName
	 * @param key
	 * @param LocalFile
	 */
	public void down(String BucketName, String key, String LocalFile){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		File file=new File(LocalFile);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 下载object到文件
		ossClient.getObject(new GetObjectRequest(BucketName, key), file);

		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 断点续传下载
	 * @param BucketName
	 * @param key
	 * @param downloadFile
	 */
	public void downBreak(String BucketName, String key, String downloadFile){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 下载请求，10个任务并发下载，启动断点续传
		DownloadFileRequest downloadFileRequest = new DownloadFileRequest(BucketName, key);
		downloadFileRequest.setDownloadFile(downloadFile);
		downloadFileRequest.setTaskNum(10);
		downloadFileRequest.setEnableCheckpoint(true);

		// 下载文件
		DownloadFileResult downloadRes = null;
		try {
			downloadRes = ossClient.downloadFile(downloadFileRequest);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 下载成功时，会返回文件的元信息
		downloadRes.getObjectMetadata();

		// 关闭client
		ossClient.shutdown();
	}
	public void main(String[] args) {
		File file = new File("C:\\Users\\Administrator\\Desktop\\黄露萱\\黄露萱\\1229_1.jpg");
		String bakeget = "iyunting";
		StringBuffer st = new StringBuffer(1024);
		Random random = new Random();
		st.append("云听/测试/").append(random.nextInt(100)).append(".jpg");
		PutObjectResult result = upload(bakeget, st.toString(), file);
		String imgurl ="img-cn-hangzhou.aliyuncs.com";
		
		StringBuffer ret = new StringBuffer(2048);
		ret.append(prefix).append("://").append(bakeget).append(".").append(imgurl).append("/").append(URLEncoder.encode(new String(st)));
		System.out.println(result.getETag());
		System.out.println(result.getRequestId());
		System.out.println(new String(ret));
		
	}
	
	/**
	 * 获取文件上传OSS服务器后返回路径
	 * @param appType		APP应用类别
	 * @param imgUrl		文件base64编码流文件
	 * @return
	 */
	public String uploadFileToOss(String appType, String imgUrl){
		String[] files = imgUrl.split("base64,");
		String baseFile = files[0];
		String[] baseFiles = baseFile.split(";");
		String suffixName = baseFiles[0].substring(11, baseFiles[0].length());		//后缀名
		BASE64Decoder decode = new BASE64Decoder();
		InputStream fileInputStream = null;
		try {
			byte[] oldbyte = decode.decodeBuffer(files[1]);
			fileInputStream = new ByteArrayInputStream(oldbyte);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filePath = getUploadFullPath("");					//获取系统生成的文件存放路径
		String fileName = getfileName(suffixName, suffixName);	//获取系统生成的文件名
		StringBuffer st = new StringBuffer(1024);
		st.append(appType).append(filePath).append(fileName);
		StringBuffer ret = new StringBuffer(2048);
		upload(backetName, new String(st), fileInputStream);
		ret.append(prefix).append("://").append(backetName).append(".").append(imgURL).append("/").append(URLEncoder.encode(new String(st)));
		return new String(ret);
	}
	
	/**
	 * 上传文件至阿里云OSS
	 * @param appType
	 * @param file
	 * @param absoluteUrl
	 * @return
	 */
	public String uploadLocalFileToOss(String appType, MultipartFile file, boolean absoluteUrl){
		String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());		//后缀名
		InputStream fileInputStream = null;
		try {
			
			fileInputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filePath = getUploadFullPath("");					//获取系统生成的文件存放路径
		String fileName = getfileName(suffixName, suffixName);	//获取系统生成的文件名
		StringBuffer st = new StringBuffer(1024);
		st.append(appType).append(filePath).append(fileName);
		StringBuffer ret = new StringBuffer(2048);
		upload(backetName, new String(st), fileInputStream);
		if (absoluteUrl) {
			ret.append(imgRoot).append(new String(st));
			return new String(ret);
		} else {
			return new String(st);
		}
		
	}
	
	public String uploadTmpFileToOss(String appType, File file){
		String suffixName = file.getName().substring(file.getName().lastIndexOf(".")+1, file.getName().length());		//后缀名
		String filePath = getUploadFullPath("");					//获取系统生成的文件存放路径
		String fileName = getfileName(suffixName, suffixName);	//获取系统生成的文件名
		StringBuffer st = new StringBuffer(1024);
		st.append(appType).append(filePath).append(fileName);
		StringBuffer ret = new StringBuffer(2048);
		upload(backetName, new String(st), file);
		ret.append(prefix).append("://").append(httpPath).append("/").append(URLEncoder.encode(new String(st)));
		return new String(ret);
	}
	
	public String uploadLocalFileToOss(String appType, InputStream inStream, String fileName){
		String suffixName = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());		//后缀名
		String filePath = getUploadFullPath("");
		StringBuffer st = new StringBuffer(1024);
		String fileName2 = getfileName(suffixName, suffixName);
		st.append(appType).append(filePath).append(fileName2);
		StringBuffer ret = new StringBuffer(2048);
		upload(backetName, new String(st), inStream);
		ret.append(prefix).append("://").append(httpPath).append("/").append(URLEncoder.encode(new String(st)));
		return new String(ret);
	}
	
	/**
	 * 后台签名阿里云OSS
	 * @param appType
	 * @param file
	 * @return
	 */
	public String PostPolicy(String appType){
		 String host = prefix + "://" + backetName + "." + endpoint2;
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		JSONObject ja1=null;
        try { 	
        	long expireTime = Long.valueOf(expireTimein);
        	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, appType);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            StringBuffer ret = new StringBuffer(2048);
    		ret.append(prefix).append("://").append(httpPath).append("/");
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //respMap.put("expire", formatISO8601Date(expiration));
            respMap.put("dir", appType);
            respMap.put("host", host);
            respMap.put("cdnPath", ret.toString());
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            ja1 = JSONObject.fromObject(respMap);
            System.out.println(ja1.toString());
        } catch (Exception e) {
        	LOGGER.error(e.getMessage());
            e.printStackTrace();
        }
		return ja1.toString();
	}


	/**
	 * 创建上传的全目录(在根目录下建立子目录),并范围子目录路径
	 * <p>
	 *
	 * @param uploadRootDir
	 * @return
	 */
	public String getUploadFullPath(String uploadType) {
		Date today = DateUtils.getCurrentDate();

		if (StringUtils.isNotBlank(uploadType)) {
			uploadType = "/" + uploadType;
		}

		String s = uploadType
				+ "/" + DateUtils.formatDate("yyyyMM", today)
				+ "/" + DateUtils.formatDate("dd", today)
				+ "/" + DateUtils.formatDate("HH", today) + "/";
		return s;
	}

	/**
	 * 生产文件名
	 * <p>
	 *
	 * @param uploadRootDir
	 * @return
	 */
	public String getfileName(String filename,String suffixName) {
		Date today = DateUtils.getCurrentDate();
		if(filename.equals(suffixName)){
			Random random = new Random();
			filename = getRandomString(random.nextInt(50));
		}
		String s = filename+ DateUtils.formatDate("yyyyMM", today)+ DateUtils.formatDate("dd", today)+ DateUtils.formatDate("HH", today)+DateUtils.formatDate("SS", today)+"."+suffixName;
		return s;
	}

	public String getRandomString(int length) { //length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
}
